package com.finalBlog.interceptor;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;

import com.finalBlog.common.AdminBaseController;
import com.finalBlog.common.Dic;
import com.finalBlog.util.CommonTools;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

/**
 * 类/接口信息描述:封装请求的参数到对应字段，便于在controller中及前端使用
 *
 * @author dengxc
 *
 */
public class ParamInterceptor implements Interceptor{
	private final Logger log = Logger.getLogger(ParamInterceptor.class);
	public void intercept(Invocation inv) {
		AdminBaseController con = (AdminBaseController) inv.getController();
		String path = con.getRequest().getContextPath();
		String basePath = con.getRequest().getScheme() + "://" + con.getRequest().getServerName() + ":"
				+ con.getRequest().getServerPort() + path;
		// 设置程序根地址
		con.getRequest().setAttribute("basePath", basePath);
		// 设置cookie map 在页面上可通过表达式即可获取相应的值
		con.getRequest().setAttribute("cookieMap", CommonTools.getCookieMap(con.getRequest()));
		Map<String, String[]> paramap = con.getParaMap();
		/*con.getRequest().setAttribute("paramMap", paramap);*/
		Class<?> childclass = con.getClass(); 
		Class<?> superclass = childclass.getSuperclass();
		Field[] childFields = childclass.getDeclaredFields();
		Field[] parentFields = superclass.getDeclaredFields();
		/*Params para = new Params();//分页对象，在BaseController 中定义
		String start = con.getRequest().getParameter("iDisplayStart");
		String pagesize = con.getRequest().getParameter("iDisplayLength");*/
		
		/*if (StrKit.notBlank(start)&&StrKit.notBlank(pagesize)&&!pagesize.equals("-1")) {
			int pagenum = (Integer.parseInt(start)/Integer.parseInt(pagesize))+1;
			para.setPageSize(Integer.parseInt(pagesize));
			para.setPageNum(pagenum);
		}
		para.setQueryParam(paramap);
		con.setPageParam(para);*/
		for(Field field:childFields){
			setControllerFieldValue(con,field);
		}
		for(Field field:parentFields){
			setControllerFieldValue(con, field);
		}
		inv.invoke();
	    for(Field field:childFields){
	    	setRequestAttrValue(con,field);
	    }
	    for(Field field:parentFields){
	    	setRequestAttrValue(con, field);
	    }
	}
	/**
	* 方法描述：封装请求参数到controller 的字段中
	*
	* @param controller
	* @param field
	* void
	*/
	public void setControllerFieldValue(Controller controller,Field field){
		try {
			field.setAccessible(true);
			String name = field.getName();
			String[] value = controller.getParaValues(name);
			if(value==null||StrKit.isBlank(value[0])){
//				log.debug("封装值到field name："+name+"为空！");
				return;
			}
			String fieldType = field.getType().getSimpleName();
			if(fieldType.equals("String[]"))
				field.set(controller, value);
			if(fieldType.equals("Integer[]")){
				Integer[] ivalues = new Integer[value.length];
				for(int i =0;i<value.length;i++){
					if(StrKit.notBlank(value[i])){
						ivalues[i] = Integer.parseInt(value[i]);
					}else{
						ivalues[i] = null;
					}
				}
				field.set(controller, ivalues);
			}
			if(fieldType.equals("String"))
				field.set(controller, value[0]);
			else if(fieldType.equals("Integer")||fieldType.equals("int"))
				field.set(controller, Integer.parseInt(value[0]));
			else if(fieldType.equals("Long"))
				field.set(controller, Long.parseLong(value[0]));
			else if(fieldType.equals("Date")){
				int datetype = value[0].trim().length();
				Date d = null;
				if(datetype<= Dic.date_ymd.length()){
					d = CommonTools.parseDate(value[0], Dic.date_ymd);
				}else if(datetype>=Dic.date_ymd_hms.length()){
					d = CommonTools.parseDate(value[0], Dic.date_ymd_hms);
				}else{
					log.debug("field name:"+name+"的值格式不正确，无法转换，将赋空值！");
				}
				field.set(controller, d);
			}else if(fieldType.equals("BigDecimal")){
				BigDecimal decimal = new BigDecimal(value[0]);
				field.set(controller, decimal);
			}else{
				log.debug("没有解析到有效字段类型");
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}finally {
			field.setAccessible(false);
		}
	}
	/**
	* 方法描述：封装controller 中的参数到request作用域
	*
	* @param controller
	* @param field
	* void
	*/
	public void setRequestAttrValue(Controller controller,Field field){
		try {
			field.setAccessible(true);
			String name = field.getName();
			Object values = field.get(controller);
			if(values==null||StrKit.isBlank(values.toString())||values instanceof Logger||values instanceof org.apache.log4j.Logger){
				return;
			}else{
				controller.getRequest().setAttribute(name, values);
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}finally {
			field.setAccessible(false);
		}
		
	}
}
